package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import cn.com.kh.batch.FCallAPI_Utils
import cn.com.kh.result.iAPIResult
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: apiBatchAuthTask
 * @Description: 定时获取法大大签署状态
 *
 */
public class apiBatchFddSignTask implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiBatchFddSignTask.class);
    private static String CC_APIDomain = "https://ronglian.dbc61.com/ngsapitask_ph/api";
    private static String APPID = "100002";
    private static String APPKEY = "E4uX9c65e5h7A5K5DA6rw6JL";

    // 获取数据库操作对象
    private static JdbcTemplate jt = new JdbcTemplate();

    // 批次启动暂停的控制Map
    private volatile static Map<String, Integer> stopFlagMap = new HashMap<String, Integer>();

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        long startTime = System.currentTimeMillis();

        jt = new JdbcTemplate(eliteBean.getDataSource());

        // 初始化返回参数
        JSONObject res_Json = iAPIResult.ERROR("获取-定时获取法大大状态 失败");

        String method = request.getMethod();
        log.debug("获取请求方式：" + method);

        // 获取所有Header
        Map<String, String> mapHeader = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("Call Header-" + key + ":" + value);

            mapHeader.put(key, value);
        }

        // 获取所有参数名
        Map<String, String> mapParam = new HashMap<String, String>();
        Enumeration ep = request.getParameterNames();
        while (ep.hasMoreElements()) {
            String key = (String) ep.nextElement();
            String value = request.getParameter(key);
            log.debug("Call Parameter-" + key + ":" + value);
            mapParam.put(key, value);

        }

        // 获取调用数据
        String callPram = "";
        if (method.equals("GET")) {
            callPram = request.getQueryString();
            log.info("接收调用GET参数信息：" + callPram);
        } else if (method.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                callPram += line;
            }
            log.info("接收调用POST报文信息：" + System.getProperty("line.separator") + callPram);
        }

        try {
            // 获取操作数据源
            jt = new JdbcTemplate(eliteBean.getDataSource());

            // 获取Fdd合同签署状态合同No
            String doc_No = Util.filterForObject(request.getParameter("doc_No"));
            log.debug("获取Fdd合同签署状态 调用参数 doc_No：" + doc_No);

            if (KHUtil.isNull(doc_No)) {
                res_Json = iAPIResult.ERROR("获取Fdd合同签署状态 doc_No不能为空");

            } else {
                res_Json = batchFDDSignFix(doc_No);

            }

        } catch (Exception e) {
            res_Json = iAPIResult.ERROR("获取Fdd合同签署状态 处理调用异常(" + e.getMessage() + ")");
            log.error("获取Fdd合同签署状态 处理调用异常：" + e.getMessage(), e);

        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "获取Fdd合同签署状态", "apiBatchFddSignTask", callPram, res_Json.toString(), (System.currentTimeMillis() - startTime).toString(), method + ":" + mapParam.toString());
        }

        log.debug("获取Fdd合同签署状态 执行结果：" + res_Json.toString());
        return res_Json.toString();
    }

    // Fix-1-获取合同签署状态
    public static JSONObject batchFDDSignFix(String doc_No) {
        return do_GetSignStateInfo(doc_No);
    }

    // Fix-2-获取合同签署状态
    public static JSONObject do_GetSignStateInfo(String doc_No) {

        JSONObject res_Json = iAPIResult.ERROR("获取合同签署状态 失败");
        try {
            // 查询-FDD-通过合同ID查询法大大合同签署状态
            String Rec_Guid = KHUtil.getRandomString(36).toUpperCase();
            res_Json = FCallAPI_Utils.getContractSignStatus(jt, Rec_Guid, doc_No);
            log.debug("☢通过合同ID查询法大大合同签署状态 :" + res_Json);

            String res_Code = KHUtil.GetSFJV(res_Json, "code");
            String res_Msg = KHUtil.GetSFJV(res_Json, "msg");
            if (res_Code.equals("1")) {
                JSONObject res_FddJson = res_Json.getJSONObject("data");
                res_Code = KHUtil.GetSFJV(res_FddJson, "code");
                res_Msg = KHUtil.GetSFJV(res_FddJson, "msg");
                if (res_Code.equals("1")) {
                    JSONObject res_FddData = res_FddJson.getJSONObject("data");
                    JSONArray res_signerList = res_FddData.getJSONArray("contractSignerList");

                    int loop_Num = 0;
                    for (int i = 0; i < res_signerList.size(); i++) {
                        JSONObject res_FddSign = res_signerList.getJSONObject(i);

                        String customerId = KHUtil.GetSFJV(res_FddSign, "customerId");
                        String signStatus = KHUtil.GetSFJV(res_FddSign, "signStatus");
                        String signStatusDesc = KHUtil.GetSFJV(res_FddSign, "signStatusDesc");
                        String signTime = KHUtil.GetSFJV(res_FddSign, "signTime");
                        String reject_Reason = signStatus.equals("2") ? "已拒签,签署状态接口无详细原因" : "";

                        updateCont_SignState(doc_No, customerId, signStatus, signStatusDesc, signTime, reject_Reason);

                        loop_Num++;

                    }

                    pushSign(jt, doc_No);

                    res_Json = iAPIResult.SUCCESS("同步法大大合同最新签署状态成功", "总签署结果:" + res_signerList.size() + " 同步成功:" + loop_Num);

                } else {
                    res_Json = iAPIResult.ERROR("⛔法大大签署状态接口失败 结果:" + res_Code + "/" + res_Msg);
                    log.warn("⛔法大大签署状态接口失败 结果:" + res_Code + "/" + res_Msg);

                }
            } else {
                res_Json = iAPIResult.ERROR("⛔内部签署状态接口失败 结果:" + res_Code + "/" + res_Msg);
                log.warn("⛔内部签署状态接口失败 结果:" + res_Code + "/" + res_Msg);

            }

        } catch (Exception e) {
            res_Json = iAPIResult.ERROR("☣内部签署状态接口 异常:" + e.getMessage());
            log.error("☣内部签署状态接口 异常", e);

        }
        return res_Json;

    }

    /* 合同签署状态数据修复 SZHJX-ZL-AC12-202311015XHp*/

    public static void updateCont_SignState(String doc_No, String customerId, String signStatus, String signStatusDesc, String signTime, String reject_Reason) {
        String updSql = "Insert Into Fdd_Agreement_List_His (Agreementduid, Modelid, Businessnumber, Workorderid, Contractid, Pushsigning, Customerid, Ht_State, Ht_Type, Pushsigningtime, Ht_Statetime, Ordernum, Transactionno, Customertype, Rejectionreason, Createddate, Createdby, Resultcode, Resultmsg, Resulttime, Pushfailreason, Pushfailtime, Del_Flag, Update_By, Update_Time) Select Agreementduid, Modelid, Businessnumber, Workorderid, Contractid, Pushsigning, Customerid, Ht_State, Ht_Type, Pushsigningtime, Ht_Statetime, Ordernum, Transactionno, Customertype, Rejectionreason, Createddate, Createdby, Resultcode, Resultmsg, Resulttime, Pushfailreason, Pushfailtime, 1, '##PULL', Now() From Fdd_Agreement_List Where Contractid = ? And Customerid = ?";
        int i_Num = jt.update(updSql, doc_No, customerId);
        log.debug("❕合同签署状态数据修复 备份数据 i_Num:" + i_Num);

        updSql = "Update Fdd_Agreement_List Set Ht_State = ?, Ht_Statetime = ?, Rejectionreason = ?, Resultcode = ?, Resultmsg = ?, Resulttime = Now() Where Contractid = ? And Customerid = ?";
        i_Num = jt.update(updSql, signStatusDesc.equals("已签") ? "已签署" : signStatusDesc, KHUtil.isNull(signTime) ? null : signTime, reject_Reason, signStatus, signStatusDesc, doc_No, customerId);
        log.debug("❕合同签署状态数据修复 更新数据 i_Num:" + i_Num);
    }


    /**
     * 3-推送签署Main
     */
    public static JSONObject pushSign(JdbcTemplate jt, String rec_Guid) {
        JSONObject res_Json = new JSONObject();

        String selectNoSignSQL = "Select If(R0.Workorderid Is Null Or R0.Workorderid = '', R1.Contractid, R0.Workorderid) As Rec_Guid, R1.Customertype, R1.Customerid, R1.Contractid, Fc.Fddgroup_Id, Replace(R1.Agreementduid, '-', '') As Agreementduid, R1.Ordernum From Fdd_Contract_List R0 Left Join Fdd_Agreement_List R1 On R0.Contractid = R1.Contractid Left Join Customer R2 On R1.Customerid = R2.Fdd_Customerid And Find_In_Set(R2.Customerid, R1.Customerid) Left Join Fdd_Contract_File Fc On R0.Contractfileid = Fc.Contractfileid Where R1.Pushsigning = '已推送' And R1.Ht_State = '未签署' And R0.Contractid = ? Order By R1.Ordernum";
        List<Map<String, Object>> signNoSignList = jt.queryForList(selectNoSignSQL, rec_Guid);
        log.debug("3-推送签署Main 检查是否存在已推送&未签署任务:" + signNoSignList.toString());

        if (signNoSignList.size() > 0) {
            log.warn("3-推送签署Main 检查是否存在已推送&未签署任务:存在未签署任务");
            res_Json = iAPIResult.WARN("推送乙方签署结束:存在未签署乙方");

        } else {

            // 查询待签署乙方
            String selectBSQL = "Select If(R0.Workorderid Is Null Or R0.Workorderid = '', R1.Contractid, R0.Workorderid) As Rec_Guid, R1.Customertype, R1.Customerid, R1.Contractid, Fc.Fddgroup_Id, Replace(R1.Agreementduid, '-', '') As Agreementduid, R1.Ordernum From Fdd_Contract_List R0 Left Join Fdd_Agreement_List R1 On R0.Contractid = R1.Contractid Left Join Customer R2 On R1.Customerid = R2.Fdd_Customerid And Find_In_Set(R2.Customerid, R1.Customerid) Left Join Fdd_Contract_File Fc On R0.Contractfileid = Fc.Contractfileid Where R1.Ht_Type = '客户' And R1.Pushsigning = '未推送' And R0.Contractid = ? Order By R1.Ordernum";
            List<Map<String, Object>> signBList = jt.queryForList(selectBSQL, rec_Guid);
            log.debug("3-推送签署Main 查询待签署乙方:" + signBList.toString());

            if (signBList.size() > 0) {
                Map<String, Object> signBMap = signBList.get(0);

                jt.update("Update Fdd_Agreement_List Set Agreementduid = ? Where R1.Contractid = ? And Replace(Agreementduid, '-', '') = ?", KHUtil.GetMapV(signBMap, "Agreementduid"), rec_Guid, KHUtil.GetMapV(signBMap, "Agreementduid"));

                res_Json = FCallAPI_Utils.pushPartyBSign(jt, rec_Guid, signBMap);

                // 解析合同生成结果
                String res_Code = KHUtil.GetSFJV(res_Json, "code");
                String res_Msg = KHUtil.GetSFJV(res_Json, "msg");
                if (res_Code.equals("1")) {
                    // 推送乙方签署结果
                    res_Json = iAPIResult.SUCCESS("推送乙方签署结束(剩余:" + (signBList.size() - 1) + ")", res_Json);
                    log.debug("推送乙方签署结果：" + res_Json);

                } else {
                    // 推送乙方签署结果
                    res_Json = iAPIResult.ERROR("推送乙方签署错误", res_Json);
                    log.debug("推送乙方签署结果：" + res_Json);

                }

            } else {
                String selectASQL = "Select If(R0.Workorderid Is Null Or R0.Workorderid = '', R1.Contractid, R0.Workorderid) As Rec_Guid, R1.Customertype, R1.Customerid, R1.Contractid, Fc.Fddgroup_Id, Replace(R1.Agreementduid, '-', '') As Agreementduid, R1.Ordernum, R1.Ht_Type From Fdd_Contract_List R0 Left Join Fdd_Agreement_List R1 On R0.Contractid = R1.Contractid Left Join Customer R2 On R1.Customerid = R2.Fdd_Customerid And Find_In_Set(R2.Customerid, R1.Customerid) Left Join Fdd_Contract_File Fc On R0.Contractfileid = Fc.Contractfileid Where R1.Ht_Type In ('公司', '法人') And R1.Pushsigning = '未推送' And R0.Contractid = ? Order By R1.Ordernum";
                List<Map<String, Object>> signAList = jt.queryForList(selectASQL, rec_Guid);
                log.debug("3-推送签署Main 查询待签署甲方:" + signAList.toString());

                if (signAList.size() > 0) {
                    Map<String, Object> signAMap = signAList.get(0);
                    // 判断是否自动归档
                    String autoArchive = signAList.size() == 1 ? "1" : "2";

                    jt.update("Update Fdd_Agreement_List Set Agreementduid = ? Where R1.Contractid = ? And Replace(Agreementduid, '-', '') = ?", KHUtil.GetMapV(signAMap, "Agreementduid"), rec_Guid, KHUtil.GetMapV(signAMap, "Agreementduid"));

                    res_Json = FCallAPI_Utils.pushPartyASign(jt, rec_Guid, signAMap, autoArchive);

                    // 解析合同生成结果
                    String res_Code = KHUtil.GetSFJV(res_Json, "code");
                    String res_Msg = KHUtil.GetSFJV(res_Json, "msg");
                    if (res_Code.equals("1")) {
                        // 推送乙方签署结果
                        res_Json = iAPIResult.SUCCESS("推送甲方签署结束(剩余:" + (signAList.size() - 1) + ")", res_Json);
                        log.debug("推送甲方签署结果：" + res_Json);

                    } else {
                        // 推送乙方签署结果
                        res_Json = iAPIResult.ERROR("推送甲方签署错误", res_Json);
                        log.debug("推送甲方签署结果：" + res_Json);

                    }

                } else {
                    res_Json = iAPIResult.ERROR("推送签署结束", "未找到待签署任务");

                }

            }
        }

        return res_Json;
    }

}